//
//  RHHousesListController.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/30.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import URLNavigator
import SVProgressHUD
private let navigator: NavigatorType = RHRouterNavigator.sharedInstance.navigator

class RHHousesListController: RHViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
    
    var searchBarView: UIView?
    var tableView: RHTableView?
    var cityName :String?
    
    var action:String?
    var keyword:String?
    var type:String?
    var beds:String?
    var baths:String?
    var year:String?
    var minSize:String?
    var maxSize:String?
    var minPrice:String?
    var maxPrice:String?
    var model = RHSearchAssociateResponseModel()
    var imageArray = NSMutableArray()
    var pageNumber = 0
    private let navigator: NavigatorType = RHRouterNavigator.sharedInstance.navigator
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("HousesTitle", comment: "")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_icon_back"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancel))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_filter"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(detailedSearch))
        
        loadTableView()
        
        if cityName != nil {
            doSearchAssociate()
        }
        
        if action != nil {
            doHousesSearch()
        }
    }
    
    @objc func detailedSearch() {
        self.present(RHCustomNavigationController(rootViewController: RHHousesDetailedSearchVC()), animated: true, completion:nil)
    }
    
    
    func doHousesSearch(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doHousesSearch(action: action!, keyword: keyword!, page: 1, type: type!, beds: Int(beds!)!, baths: Int(baths!)!, year: Int(year!)!, minSize: Int(minSize!)!, maxSize: Int(maxSize!)!, minPrice: Int(minPrice!)!, maxPrice: Int(maxPrice!)!, result: { (msg, data) in
            SVProgressHUD.dismiss()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: msg)
        }
    }
    
    func doSearchAssociate(){
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doSearchAssociate(keyword: self.cityName!, result: {[weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.model = data as! RHSearchAssociateResponseModel
            weakSelf.tableView?.reloadData()
        }) { (code, msg) in
            SVProgressHUD.dismiss()
        }
    }
    
    @objc func cancel() {
        self.navigationController?.popViewController(animated: true)
//        self.dismiss(animated: false, completion: nil)
    }
    
    func loadTableView() {
        self.tableView = RHTableView(frame: CGRect.zero, style: .plain)
        self.tableView?.delegate = self;
        self.tableView?.dataSource = self;
        self.tableView?.register(RHImageTableViewCell.self, forCellReuseIdentifier: "RHImageTableViewCell")
        self.view.addSubview(self.tableView!)
        
        self.tableView?.snp.makeConstraints { [weak self](make) in
            guard let weakSelf = self else { return }
            make.top.equalTo(10)
            make.left.equalTo(weakSelf.view.snp.left)
            make.right.equalTo(weakSelf.view.snp.right)
            make.bottom.equalTo(weakSelf.view.snp.bottom)
        }
    }
    
    @objc func previousPageButtonClick() {
        if pageNumber > 0 {
            pageNumber = pageNumber - 1
        }
    }
    
    @objc func nextPageButtonClick() {
        pageNumber = pageNumber + 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.model.address == nil {
            return 0
        }
        for _ in self.model.address! {
            imageArray.add(UIImage(named: "placeholder")!)
        }
        return (self.model.address?.count)!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: RHImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHImageTableViewCell", for: indexPath) as! RHImageTableViewCell

        cell.titleLabel?.text = self.cityName
        cell.contentLabel?.text = self.model.address?[indexPath.row].address

        if cell.leftImageView?.image == nil {
            if self.model.address?[indexPath.row].photo != nil {
                let url = URL(string: (self.model.address?[indexPath.row].photo)!)
                let request =  URLRequest(url: url!)
                let session  = URLSession.shared
                let dataTask = session.dataTask(with: request, completionHandler: {
                    (data, response, taskError) -> Void in
                    if taskError != nil{
                        print(taskError.debugDescription)
                    }else{
                        DispatchQueue.main.async {
                            self.imageArray.replaceObject(at: indexPath.row, with: UIImage(data: data!)!)
                            cell.leftImageView?.image = (self.imageArray[indexPath.row] as! UIImage)
                        }
                    }
                }) as URLSessionTask
                dataTask.resume()
            }else{
                cell.leftImageView?.image = (imageArray[indexPath.row] as! UIImage)
            }
        }else{
            cell.leftImageView?.image = (imageArray[indexPath.row] as! UIImage)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = RHHouseDetailsVC()
        vc.houseId = (self.model.address?[indexPath.row].houseId)!
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
